package org.apache.ocean.main.http;

import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ocean.main.util.NamedList;

/**
 * 
 * @author jasonr
 */
public class HttpParameters extends NamedList<String, String> {
	public HttpParameters(Object... objects) {
		for (int x = 0; x < objects.length; x = x + 2) {
			String name = (String) objects[x];
			String value = objects[x + 1].toString();
			add(name, value);
		}
	}
  
	public BigInteger getBigInteger(String name) {
		String value = get(name);
		if (StringUtils.isBlank(value)) return null;
		return new BigInteger(value);
	}
	
	public URL getUrl(String name) throws MalformedURLException {
		String value = get(name);
		if (StringUtils.isBlank(value)) return null;
		return new URL(value);
	}
	
	public Integer getInt(String name, Integer defaultValue) {
		String value = get(name);
		if (StringUtils.isBlank(value)) {
			if (defaultValue != null) return defaultValue;
			else return null;
		}
		return new Integer(value);
	}
	
	public Integer getInt(String name) {
		return getInt(name, null);
	}
	
	public Long getLong(String name, long defaultValue) {
		Long value = getLong(name);
		if (value == null) return defaultValue;
		return value;
	}
	
	public Long getLong(String name) {
		String value = get(name);
		if (StringUtils.isBlank(value)) return null;
		return new Long(value);
	}

	public boolean has(String name, String equalsValue) {
		String value = get(name);
		return StringUtils.equals(value, equalsValue);
	}

	public String toEncodedQueryString() {
		String queryString = EncodingUtil.formUrlEncode(CHttpClient.toNameValuePairs(this), "UTF-8");
		return queryString;
	}

	public void add(String key, Object value) {
		if (StringUtils.isBlank(key) || value == null)
			return;
		add(key, value.toString());
	}

	public void add(String key, String value) {
		if (StringUtils.isBlank(key) || StringUtils.isBlank(value))
			return;
		super.add(key, value);
	}

	public HttpParameters(String... strings) {
		for (int x = 0; x < strings.length; x = x + 2) {
			String name = strings[x];
			String value = strings[x + 1];
			add(name, value);
		}
	}
}
